package com.intro.action;

import java.io.File;

import javax.persistence.Entity;

import org.apache.struts2.ServletActionContext;

import com.intro.database.entity.Image;
import com.intro.database.entity.News;
import com.intro.manager.INewsManager;
import com.intro.manager.impl.NewsManagerImpl;
import com.opensymphony.xwork2.ActionSupport;

@Entity
public class EditNewsAction extends ActionSupport {
	
	private String content;
	
	private String title;
	
	private String image_src;
	
	private String news_id;
	
	private INewsManager newsManager = new NewsManagerImpl();
	
	public String execute() throws Exception {
		String result;
		News news = newsManager.findByNewsId(Integer.valueOf(news_id));
		if(news!=null) {
			String p;
			for (Image image : news.getImages()) {
				p = ServletActionContext.getRequest().getParameter(image.getImageId()+"");
				if(!image.getImageSrc().equals(p)) {
					deletePic(image.getImageSrc());
					image.setImageSrc(p);
				}
			}
			if(!image_src.trim().equals("")) {
				String[] imagepaths = image_src.split(":");
				for(int i = 0;i<imagepaths.length;i++) {
					Image image = new Image();
					image.setImageSrc(imagepaths[i]);
					news.getImages().add(image);
				}
			}
			/*if(true) {
				return ERROR;
			}*/
			/*if(!news.getImagePath().endsWith(image_src)) {
				deletePic(news.getImagePath());
			}*/
			news.setContent(content);
			news.setTitle(title);
			news.setImagePath(image_src);
			newsManager.updateNews(news);
			ServletActionContext.getRequest().setAttribute("type", news.getType());
		} else {
			return ERROR;
		}
		return SUCCESS;
	}

	public String getContent() {
		return content;
	}

	public void setContent(String content) {
		this.content = content;
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public String getImage_src() {
		return image_src;
	}

	public void setImage_src(String imageSrc) {
		image_src = imageSrc;
	}

	public void setNews_id(String news_id) {
		this.news_id = news_id;
	}
	
	private void deletePic(String path) {
		String rootPath = ServletActionContext.getServletContext().getRealPath("");
		System.out.println(rootPath);
		File f = new File(rootPath+"\\"+path);
		if(f.exists())
			f.delete();
	}
	

}
